<?php
class PushShell extends AppShell
{
    public $uses = array('account');

    public function push_set()
    {
        $data['game_name'] = $this->args['game_name'];
        $data['title'] = base64_encode($this->args['title']);
        $data['msg'] = base64_encode($this->args['msg']);

        $path = str_replace('\webroot', '', WWW_ROOT);
        $cake_app = 'start cmd /c cake -app ';
        $user_count = $this->account->get_user_count($data['game_name']);

        if($user_count >= 1 && $user_count <= 10000) $command_max = 1;
        else if($user_count >= 10001 && $user_count <= 100000) $command_max = 10;
        else if($user_count >= 100001 && $user_count <= 500000) $command_max = 20;
        else $command_max = 30;

        pr('user count : ' . $user_count);
        pr('max : ' . $command_max);

        $start_limit    = 0;
        $limit          = round($user_count/$command_max);

        for($i=1; $i<=$command_max; $i++)
        {
            $result = $cake_app.$path.' '.$this->name.' push_send'.' '.'"'.$data['game_name'].'"'.' '.'"'.$data['title'].'"'.' '.'"'.$data['msg'].'" '.$start_limit.' '.$limit;
            $fp = popen($result, 'r');
            pclose($fp);

            $start_limit += $limit;
            usleep(1000000);
        }
    }

    public function push_send()
    {
        $game_name = $this->args[0];

        $data = array(
            'title' => base64_decode($this->args[1]),
            'msg' => base64_decode($this->args[2]),
        );

        $start_limit    = $this->args[3];
        $end_limit      = $this->args[4];

        $start_count    = 0;
        $end_count      = 1000;
        $count          = 1000;
        $num            = 0;

        $push_list = $this->account->get_push_id_list($start_limit, $end_limit, $game_name);

        $android_push_id = '';
        $ios_push_id = '';

        foreach($push_list as $value)
        {
            if($value['os'] == ANDROID)
            {
                $android_push_id[$num][] = $value['push_id'];
                $start_count ++;
            }

            if($value['os'] == IOS)
            {
                $ios_push_id[] = $value['push_id'];
            }

            if($start_count == $end_count)
            {
                $num++;
                $end_count += $count;
            }
        }

        if(!empty($android_push_id))
        {
            foreach($android_push_id as $send_id)
            {
                if(!gcm_push($data, $send_id))
                {
                    return error_common($this, __LINE__, GCM_ERROR);
                }
            }
        }

        if(!empty($ios_push_id))
        {
            if(!apns_push($data, $ios_push_id))
            {
                return error_common($this, __LINE__, APNS_ERROR);
            }
        }
    }
}

